/**
 * lilang
 * MailServiceImpl.java
 * 2013-9-26下午2:14:37
 */
package com.cq.oa.service.pof.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import oa.base.service.impl.BaseServiceImpl;
import oa.base.session.SessionManger;
import oa.base.util.FileUtils;
import oa.base.util.Page;

import com.cq.oa.dao.pof.MailDao;
import com.cq.oa.dao.pof.MailRecordDao;
import com.cq.oa.dao.sm.FileDao;
import com.cq.oa.domain.dto.MailDto;
import com.cq.oa.domain.pof.Mail;
import com.cq.oa.domain.pof.MailRecord;
import com.cq.oa.domain.sm.SmFile;
import com.cq.oa.domain.sm.User;
import com.cq.oa.service.pof.MailService;
import com.cq.oa.service.sm.UserService;
import com.cq.oa.utils.MailUtil;
import com.cq.oa.utils.NullUtil;
import com.cq.oa.utils.PatternUtil;
import com.cq.oa.utils.StringliptUtil;

/**
 * @author lilang
 *
 */
public class MailServiceImpl extends BaseServiceImpl<Mail> implements MailService{

	private MailDao mailDao;
	
	private MailRecordDao mailRecordDao;
	
	private UserService userService;
	
	private FileDao fileDao;

	public void setMailDao(MailDao mailDao) {
		this.mailDao = mailDao;
	}

	public void setMailRecordDao(MailRecordDao mailRecordDao) {
		this.mailRecordDao = mailRecordDao;
	}

	

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setFileDao(FileDao fileDao) {
		this.fileDao = fileDao;
	}

	/* (non-Javadoc)
	 * @see com.cq.oa.service.pof.MailService#doSendMail(com.cq.oa.domain.pof.Mail, java.lang.String)
	 */
	public Long doSendMail(Mail mail, String attrId) {
		initSave(mail);
		List<String> sendRec = new ArrayList<String>();
		Long sid = this.mailDao.create(mail);
		Long size = 0l;
		if(NullUtil.isNotEmpty(attrId)){
			size = this.fileDao.updateFileparams(StringliptUtil.splitString(attrId), sid);
		}
		size = size + mail.getMsg().length();
		mail.setMailSize(String.valueOf(size));
		this.getEmail(mail, sendRec);
		List<User> sendUser = userService.findUserByEmail(sendRec);
		List<MailRecord> mailRecords = bulidRecord(mail, sendUser);
		mailRecords.add(createRecord(sid,mail));
		this.mailRecordDao.saveAll(mailRecords);
		return sid;
	}
	
	/**
	 * 提取Email和名称
	 * @param mail
	 * @param emails
	 * @param names
	 * lilang 
	 * 2013-10-9上午10:55:35
	 */
	private void getEmail(Mail mail,List<String> emails){
		if (null != mail) {
			// 主送
			sendMailPerson(emails,mail.getSendTo());
			if (null != mail.getCopyTo()) {
				sendMailPerson(emails,mail.getCopyTo());
			}
			if (null != mail.getBccTo()) {
				sendMailPerson(emails, mail.getBccTo());
			}
		}
	}
	
	
	/**
	 * 邮件人拆分
	 * 
	 * @author: lilang
	 * @param sends
	 */
	private void sendMailPerson(List<String> sendMails, String sends) {
		String[] bccs = sends.split(",");
		for (String b : bccs) {
			// 验证邮箱格式
			String rightMail = PatternUtil.singleOutEmail(b);
			if (null != rightMail) {
				sendMails.add(rightMail);
			}
		}
	}
	
	/**
	 * 初始化数据
	 * 
	 * @author: lilang
	 * @param entity
	 */
	private void initSave(Mail entity) {
		if (null == entity) {
			entity = new Mail();
		}
		if (entity.getBackStatus() != null && entity.getBackStatus() == 1) {
			entity.setBackStatus(0);
		}
		if (null == entity.getIsUrgent()) {
			// 默认非紧急
			entity.setIsUrgent(0);
		}
		entity.setSendCname(SessionManger.getCname());
		entity.setSendId(SessionManger.getUserId());
		entity.setSendEmail(SessionManger.getEmail());
		entity.setSendTime(new Date());
		this.mailDao.initBase(entity);
	}
	
	
	/**
	 * 组装发送人基本信息
	 * 
	 * @return
	 */
	private MailRecord createRecord(Long sid,Mail mail) {
		// 组装发送人信息
		MailRecord sendRecord = new MailRecord();
		sendRecord.setOperationType(MailUtil.MAIL_SEND);
		sendRecord.setSendTime(new Date());
		sendRecord.setSenderCname(SessionManger.getCname());
		sendRecord.setSenderEmail(SessionManger.getEmail());
		sendRecord.setSenderSid(SessionManger.getUserId());
		sendRecord.setOwnerSid(SessionManger.getUserId());
		sendRecord.setReadFlag(MailUtil.MAIL_READ_FLAG_READ);
		sendRecord.setPofMailFolderSid(MailUtil.MAIL_FOLDER_FLAG_OUTBOX);
		sendRecord.setPofMailSid(sid);
		sendRecord.setTitle(mail.getTitle());
		sendRecord.setReceiverCname(mail.getSendTo());
		this.mailRecordDao.initBase(sendRecord);
		return sendRecord;
	}
	
	private List<MailRecord> bulidRecord(Mail mail,List<User> users){
		List<MailRecord> records = new ArrayList<MailRecord>();
		for(User smUser:users){
			MailRecord logs = new MailRecord();
			logs.setPofMailSid(mail.getSid());
			logs.setOperationType(MailUtil.MAIL_RECV);
			logs.setSendTime(mail.getSendTime());
			logs.setSenderCname(mail.getSendCname());
			logs.setSenderEmail(mail.getSendEmail());
			logs.setSenderSid(mail.getSendId());
			logs.setOwnerSid(smUser.getSid());
			logs.setTitle(mail.getTitle());
			logs.setReadFlag(MailUtil.MAIL_READ_FLAG_UNREAD);
			logs.setReceiverCname(smUser.getCname());
			logs.setReceiverEmail(smUser.getEmail());
			logs.setReceiverSid(smUser.getSid());
			logs.setPofMailFolderSid(MailUtil.MAIL_FOLDER_FLAG_INBOX);
			this.mailRecordDao.initBase(logs);
			records.add(logs);
		}
		return records;
	}

	/* (non-Javadoc)
	 * @see com.cq.oa.service.pof.MailService#findByPageCord(java.util.Map, int, int)
	 */
	@SuppressWarnings("unchecked")
	public Page<MailRecord> findByPageCord(Map<String, Object> filterMap,Map<String, Object> sortMap,int pageNo, int pageSize) {
		return this.mailRecordDao.pagedQuery(filterMap, sortMap, pageNo, pageSize,MailRecord.class);
	}

	/* (non-Javadoc)
	 * @see com.cq.oa.service.pof.MailService#detail(java.lang.Long)
	 */
	public MailDto detail(Long sid) throws Exception {
		MailDto dto = new MailDto();
		MailRecord mailRecord = this.mailRecordDao.get(sid);
		if(null==mailRecord){
			throw new Exception("错误的邮件记录ID:"+sid);
		}
		dto.setMailRecord(mailRecord);
		dto.setMail(this.mailDao.get(mailRecord.getPofMailSid()));
		dto.setSmFiles(this.fileDao.findByBusiness(dto.getMail().getSid(), "Mail"));
		return dto;
	}

	/* (non-Javadoc)
	 * @see com.cq.oa.service.pof.MailService#deleteRecord(java.lang.Long)
	 */
	public void deleteRecord(Long sid) {
		MailRecord mailRecord = this.mailRecordDao.get(sid);
		Long mailId  = mailRecord.getPofMailSid();
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("pofMailSid", mailId);
		Long count = mailRecordDao.findByCount(params, MailRecord.class);
		//如果只有当前这一条记录了删除原始邮件数据
		if(count==1l){
			mailDao.removeById(mailId);
			List<SmFile> smFiles=fileDao.findByBusiness(mailId, "Mail");
			for(SmFile file:smFiles){
				FileUtils.deleteFile(new File(file.getUrl()));
			}
			fileDao.removeAll(smFiles);
		}
		this.mailRecordDao.remove(mailRecord);
	}
	
	
	
	
}
